"use client";

import { useState } from "react";
import { createSession, CreateSessionReq, CreateSessionRes } from "@/lib/api/session";
import { useSessionState } from "./useSessionState";

export function useCreateSession() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { switchToSession } = useSessionState();

  async function run(payload: CreateSessionReq): Promise<CreateSessionRes> {
    setError(null);
    setLoading(true);
    try {
      const res = await createSession(payload);
      switchToSession(res.sessionId);  
      return res;
    } catch (e: any) {
      setError(e?.message ?? "Failed to create session");
      throw e;
    } finally {
      setLoading(false);
    }
  }

  return { run, loading, error };
}